package com.spic.system.service.impl;

import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.security.service.TokenService;
import com.spic.system.api.RemoteFileService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysDept;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.dto.SysFileRecord;
import com.spic.system.api.model.LoginUser;
import com.spic.system.domain.SysAnnounce;
import com.spic.system.domain.SysAnnounceReader;
import com.spic.system.domain.SysAnnounceReceiver;
import com.spic.system.domain.vo.SysAnnounceReaderVo;
import com.spic.system.mapper.SysAnnounceMapper;
import com.spic.system.mapper.SysAnnounceReaderMapper;
import com.spic.system.service.ISysAnnounceReaderService;
import com.spic.system.service.ISysAnnounceReceiverService;
import com.spic.system.service.ISysAnnounceService;
import com.spic.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 发布公示公告内容Service业务层处理
 *
 * @author spic
 * @date 2022-06-15
 */
@Service
public class SysAnnounceServiceImpl implements ISysAnnounceService
{
    @Autowired
    private SysAnnounceMapper sysAnnounceMapper;
    @Autowired
    private ISysAnnounceReceiverService sysAnnounceReceiverService;
    @Autowired
    private ISysAnnounceReaderService sysAnnounceReaderService;

    @Autowired
    private SysAnnounceReaderMapper sysAnnounceReaderMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
   private RemoteFileService remoteFileService;

    /**
     * 查询发布公示公告内容
     *
     * @param id 发布公示公告内容主键
     * @return 发布公示公告内容
     */
    @Override
    public SysAnnounce selectSysAnnounceById(Long id)
    {
        SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
        sysAnnounceReceiver.setAnnounceId(id);
        SysAnnounce s = sysAnnounceMapper.selectSysAnnounceById(id);
        // List<SysAnnounceReceiver> sysAnnounceReceiverList = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
        // List<String> uIdList = new ArrayList<>();
        // for (SysAnnounceReceiver announceReceiver : sysAnnounceReceiverList)
        // {
        //     Long userId = announceReceiver.getUserId();
        //     uIdList.add(userId+"");
        // }
        // String userIds = uIdList.stream().collect(Collectors.joining(","));
        // s.setUserIds(userIds);
        if (!CollectionUtils.isEmpty(s.getSysAnnounceReceiverList())){
            String userIds = s.getSysAnnounceReceiverList().get(0).getUserId().toString();
            SysUser sysUser = remoteUserService.getUserById(Long.parseLong(userIds)).getData();
            SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
            while (100 != sysDept.getParentId()){
                sysDept = deptService.selectDeptById(sysDept.getParentId());
                if (0 == sysDept.getParentId()){
                    break;
                }
            }
            userIds = sysDept.getDeptId() + "," + userIds;
            s.setUserIds(userIds);
        }
        return s;
    }

    /**
     * 查询发布公示公告内容列表
     *
     * @param sysAnnounce 发布公示公告内容
     * @return 发布公示公告内容
     */
    @Override
    public List<SysAnnounce> selectSysAnnounceList(SysAnnounce sysAnnounce)
    {
        List<SysAnnounce> sysAnnounceList = sysAnnounceMapper.selectSysAnnounceList(sysAnnounce);
        sysAnnounceList.forEach(info->{
            Long id = info.getId();
            SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
            sysAnnounceReceiver.setAnnounceId(id);
            List<SysAnnounceReceiver> sysAnnounceReceiverList = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
            for (SysAnnounceReceiver announceReceiver : sysAnnounceReceiverList)
            {
                info.setState("0");
                String state = announceReceiver.getState();
                if("1".equals(state)){
                    info.setState("1");
                    break;
                }
            }
        });
        return sysAnnounceList;
    }

    /**
     * 新增发布公示公告内容
     *
     * @param sysAnnounce 发布公示公告内容
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertSysAnnounce(SysAnnounce sysAnnounce)
    {
        try
        {
            String displayDuration = sysAnnounce.getDisplayDuration();
            String releaseType = sysAnnounce.getReleaseType();

            sysAnnounce.setCreateTime(DateUtils.getNowDate()); //发布时间
            sysAnnounce.setCreateBy(SecurityUtils.getUserId() + ""); //发布人
            sysAnnounceMapper.insertSysAnnounce(sysAnnounce);
            Long id = sysAnnounce.getId();
             //部门级的
            if("2".equals(releaseType)){
                String userIds = sysAnnounce.getUserIds();//接收人列表
                String[] userIdList = userIds.split(",");
                if (userIdList != null && userIdList.length > 0)
                {
                    for (String userId : userIdList)
                    {
                        SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
                        sysAnnounceReceiver.setAnnounceId(id);
                        sysAnnounceReceiver.setUserId(Long.valueOf(userId));
                        sysAnnounceReceiverService.insertSysAnnounceReceiver(sysAnnounceReceiver);
                    }
                }
            } else {   //矿级的
                SysAnnounceReader reader = new SysAnnounceReader();
                reader.setAnnounceId(id);
                Date nowDate = DateUtils.getNowDate();
                reader.setCreateBy(SecurityUtils.getUserId() + "");
                reader.setCreateTime(nowDate);
                //给当前时间加 n小时
                Calendar cal = Calendar.getInstance();
                cal.setTime(nowDate);
                cal.add(Calendar.HOUR, Integer.parseInt(displayDuration));
                reader.setEndTime(cal.getTime());
                sysAnnounceReaderMapper.insertSysAnnounceReader(reader);
            }
        }catch (Exception e){
                throw e;
        }
    }

    /**
     * 修改发布公示公告内容
     *
     * @param sysAnnounce 发布公示公告内容
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSysAnnounce(SysAnnounce sysAnnounce)
    {
        try
        {
            SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
            sysAnnounceReceiver.setAnnounceId(sysAnnounce.getId());
            List<SysAnnounceReceiver> sysAnnounceReceiverList = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
            for (SysAnnounceReceiver announceReceiver : sysAnnounceReceiverList)
            {
                Long id = announceReceiver.getId();
                sysAnnounceReceiverService.deleteSysAnnounceReceiverById(id);
            }
            String userIds = sysAnnounce.getUserIds();
            String[] userIdList = userIds.split(",");
            if (userIdList != null && userIdList.length > 0)
            {
                for (String userId : userIdList)
                {
                    SysAnnounceReceiver receiver = new SysAnnounceReceiver();
                    receiver.setAnnounceId(sysAnnounce.getId());
                    receiver.setUserId(Long.valueOf(userId));
                    sysAnnounceReceiverService.insertSysAnnounceReceiver(receiver);
                }
            }

            sysAnnounce.setUpdateTime(DateUtils.getNowDate());
            sysAnnounce.setUpdateBy(SecurityUtils.getUserId()+"");
            sysAnnounceMapper.updateSysAnnounce(sysAnnounce);
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 批量删除发布公示公告内容
     *
     * @param ids 需要删除的发布公示公告内容主键
     * @return 结果
     */
    @Override
    public void deleteSysAnnounceByIds(Long[] ids)
    {
         sysAnnounceMapper.deleteSysAnnounceByIds(ids);
    }

    /**
     * 删除发布公示公告内容信息
     *
     * @param id 发布公示公告内容主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteSysAnnounceById(Long id)
    {
        try
        {
            SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
            sysAnnounceReceiver.setAnnounceId(id);
            List<SysAnnounceReceiver> sysAnnounceReceivers = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
               if(sysAnnounceReceivers!=null && sysAnnounceReceivers.size()>0){
                   for (SysAnnounceReceiver announceReceiver : sysAnnounceReceivers)
                   {
                       Long aId = announceReceiver.getId();
                       sysAnnounceReceiverService.deleteSysAnnounceReceiverById(aId);
                       SysAnnounceReader sysAnnounceReader = new SysAnnounceReader();
                       sysAnnounceReader.setReceiverId(aId);
                       List<SysAnnounceReader> sysAnnounceReaders = sysAnnounceReaderService.selectSysAnnounceReaderList(sysAnnounceReader);
                       if(sysAnnounceReaders!=null && sysAnnounceReaders.size()>0){
                           for (SysAnnounceReader announceReader : sysAnnounceReaders)
                           {
                               Long id1 = announceReader.getId();
                               sysAnnounceReaderService.deleteSysAnnounceReaderById(id1);
                           }
                       }
                   }
               }
            sysAnnounceMapper.deleteSysAnnounceById(id);
        }catch (Exception e){
            throw e;
        }
    }

    @Override
    public List<SysAnnounce> selectSysAnnounceAuthList(SysAnnounce sysAnnounce)
    {
        List<SysAnnounce> sysAnnounceList = sysAnnounceMapper.selectSysAnnounceAuthList(sysAnnounce);
        sysAnnounceList.forEach(info->{
            Long id = info.getId();
            info.setState("0");
            SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
            sysAnnounceReceiver.setAnnounceId(id);
            sysAnnounceReceiver.setUserId(SecurityUtils.getUserId());

            List<SysAnnounceReceiver> sysAnnounceReceiverList = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
            for (SysAnnounceReceiver announceReceiver : sysAnnounceReceiverList)
            {
                String state = announceReceiver.getState();
                if("1".equals(state)){
                    info.setState("1");
                }
            }

            // 获取当前的用户
            LoginUser loginUser = tokenService.getLoginUser();
            if (StringUtils.isNotNull(loginUser))
            {
                SysUser currentUser = loginUser.getSysUser();
                // 如果是超级管理员，不能授权
                if (StringUtils.isNotNull(currentUser) && currentUser.isAdmin())
                {
                    info.setState("1");
                }
            }
        });
        return sysAnnounceList;
    }

    /**
     *  根据 announceId 查询未读人员
     * @return
     */
    @Override
    public List<SysAnnounceReaderVo> selectReaderInfoByAnnounceId(SysAnnounceReaderVo sysAnnounceReaderVo)
    {
        Long announceId = sysAnnounceReaderVo.getId();
        List<SysAnnounceReaderVo> sysAnnounceReaderVoList = sysAnnounceReaderMapper.selectSysAnnounceReaderListByAnnounceId(announceId,null);
        return sysAnnounceReaderVoList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSysAnnounceAuth(SysAnnounce sysAnnounce)
    {
        try
        {
            SysAnnounceReceiver sysAnnounceReceiver = new SysAnnounceReceiver();
            sysAnnounceReceiver.setAnnounceId(sysAnnounce.getId());
            sysAnnounceReceiver.setUserId(SecurityUtils.getUserId());
            List<SysAnnounceReceiver> sysAnnounceReceiverList = sysAnnounceReceiverService.selectSysAnnounceReceiverList(sysAnnounceReceiver);
            for (SysAnnounceReceiver announceReceiver : sysAnnounceReceiverList)
            {
                //阅读人
                String userIds = sysAnnounce.getUserAuthIds();
                String displayDuration = sysAnnounce.getDisplayDuration();
                String[] userIdList = userIds.split(",");
                if (userIdList != null && userIdList.length > 0)
                {
                    for (String userId : userIdList)
                    {
                        SysAnnounceReader sysAnnounceReader = new SysAnnounceReader();
                        sysAnnounceReader.setUserId(Long.valueOf(userId));
                        sysAnnounceReader.setReceiverId(announceReceiver.getId());
                        sysAnnounceReader.setIsRead("0");
                        Date nowDate = DateUtils.getNowDate();
                        sysAnnounceReader.setCreateTime(nowDate);
                        sysAnnounceReader.setCreateBy(SecurityUtils.getUserId()+"");

                        //给当前时间加 n小时
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(nowDate);
                        cal.add(Calendar.HOUR, Integer.parseInt(displayDuration));
                        sysAnnounceReader.setEndTime(cal.getTime());
                        sysAnnounceReaderService.insertSysAnnounceReader(sysAnnounceReader);
                    }
                }
                SysAnnounceReceiver receiver = new SysAnnounceReceiver();
                receiver.setId(announceReceiver.getId());
                receiver.setState("1");
                sysAnnounceReceiverService.updateSysAnnounceReceiver(receiver);
            }
            sysAnnounce.setUpdateTime(DateUtils.getNowDate());
            sysAnnounce.setUpdateBy(SecurityUtils.getUserId()+"");
            sysAnnounceMapper.updateSysAnnounce(sysAnnounce);
        }catch (Exception e){
            throw e;
        }
    }
    @Override
    public SysAnnounce selectSysAnnounceAuthById(Long id)
    {
        SysAnnounce s = sysAnnounceMapper.selectSysAnnounceById(id);
        //附件文件路径/名称
        String file = s.getFile();
        String url = file.substring(0, file.indexOf("|"));
        SysFileRecord fileRecord = remoteFileService.getFileByUrl(url).getData();
        s.setTransformedUrl(fileRecord.getTransformedUrl());
        s.setFileName(fileRecord.getName());
        s.setExt(fileRecord.getExt());
        s.setOriginalUrl(fileRecord.getUrl());
        s.setFileId(fileRecord.getId());
        if (!CollectionUtils.isEmpty(s.getSysAnnounceReceiverList())){
            String userIds = s.getSysAnnounceReceiverList().get(0).getUserId().toString();
            SysUser sysUser = remoteUserService.getUserById(Long.parseLong(userIds)).getData();
            SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
            while (100 != sysDept.getParentId()){
                sysDept = deptService.selectDeptById(sysDept.getParentId());
                if (0 == sysDept.getParentId()){
                    break;
                }
            }
            userIds = sysDept.getDeptId() + "," + userIds;
            s.setUserIds(userIds);
        }
        return s;
    }


    @Override
    public List<Map<String, String>> getCountByType() {
        Long userId = SecurityUtils.getUserId();
        List<Map<String, String>> maps = sysAnnounceReaderMapper.selectCountByType(userId);
        return maps;
    }
    //广告机值班人员
    @Override
    public String getPersonnelDuty()
    {
        String msg = remoteUserService.selectConfigByKey("announce.personnel.duty").getMsg();
        return msg;
    }

}
